package cn.airfei.netty.nettyexample.rpc.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @description:
 * @author: air
 * @create: 2021-01-22 15:42
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    private ChannelHandlerContext context;
    private String result;
    private String para;

    // 与服务器连接,创建成功后就会被调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context=ctx;


    }

    // 收到服务器回应后调用
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
      result=msg.toString();
      // 唤醒等待的线程
      notify();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    // 被代理的对象调用,发送数据给服务器, wait->等待被唤醒->返回结果
    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(para);
        // 等待channelRead 方法获取到服务器的结果后,唤醒
        wait();

        return result;
    }

    void setPara(String para){
        this.para=para;
    }
}
